'''
cron jobs
'''
from google.appengine.ext import webapp
from iform_util import sync_compaction_test, sync_compaction_form
import logging, model, datetime
from google.appengine.api import memcache
from ft_table import ft
import dlz_config as dc

def exe_failed_sql():
    '''
    scan the SqlReqeust table and execute the failed sql
    '''
    logging.info('execute failed sqls:')
    f = ft(None, None)
   
    for s in model.SqlRequest.all().filter('status =', 'new'):
        try:
            f.SqlQuery(s.sql)
            logging.info('success: %s' % s.sql)
            s.delete()
        except:
            s.mtime = datetime.datetime.now()
            s.put()
            logging.info(' fail: %s' % s.sql)
        
        


def exe_failed_sync():
    '''
    scan the SqlReqeust table and execute the failed sql
    '''
    logging.info('execute failed sync:')
    
    for s in model.IformDatabaseLog.all():
        if s.table=='compaction_form':
            try:
                sync_compaction_form()
                s.delete()
                logging.info('sync compaction_form success.')
            except:
                logging.info('sync compaction_form failed.')
                s.mtime = datetime.datetime.now()
                s.put()
        elif s.table=='compaction_test':
            try:
                sync_compaction_test()
                s.delete()
                logging.info('sync compaction_form success.')
            except:
                s.mtime = datetime.datetime.now()
                s.put()
                logging.info('sync compaction_form failed.')



def sync_iform():
    memcache.flush_all()
    try:
        sync_compaction_test()
        logging.info('sync compaction_test success')
    except:
        s = model.IformDatabaseLog()
        s.table = 'compaction_test'
        s.put()
        logging.info('sync compaction_test failed')
    try:
        sync_compaction_form()
        logging.info('sync compaction_form success')
        
    except:
        s = model.IformDatabaseLog()
        s.table = 'compaction_form'
        s.put()
        logging.info('sync compaction_test failed')
    memcache.flush_all()    

class CronHandler(webapp.RequestHandler):
    def get(self):
        self.post()
    def post(self):
        action = self.request.get('action')
        logging.info('cron job action=%s' % action)
        if action=='sync_compaction_form':
            sync_compaction_form()
        elif action=='sync_compaction_test':
            sync_compaction_test()
        elif action=='sync_iform':
            sync_iform()
        elif action=='exe_failed_sql':
            exe_failed_sql()
        elif action=='exe_failed_sync':
            exe_failed_sync()
        elif action=='flush_memcache':
            memcache.flush_all()
        elif action=='reload_memcache':
            dc._init()
        